const { exec } = require('child_process');
const fs = require("fs");
const path = require("path");
const os = require("os");
const ffmpegPath = path.join('./', 'ffmpeg', 'ffmpeg.exe');
const readSetting = require("../../lib/read_setting");

const speedMap = new Map([
    [1, 1.0],
    [1.5, 0.75],
    [2, 0.5],
])


module.exports = (req, res) => {

    let { findPath, speed, oldname, newname, outputPath, delSource, currentIndex } = req.body;

    speed = speed * 1;

    outputPath = outputPath || readSetting().output_path || path.join(os.homedir(), 'Desktop');

    if (!speedMap.get(speed)) return res.send({ code: 400, msg: "未设置倍速", result: '', ...req.body });

    if (!findPath.trim()) return res.send({ code: 400, msg: "参数被恶意纂改", result: '', ...req.body });

    if (!oldname.trim()) return res.send({ code: 400, msg: "参数被恶意纂改", result: '', ...req.body });

    if (!newname.trim()) newname = oldname;

    if (!/\.(mp4|avi|wmv|flv)$/.test(newname)) newname = `${newname}.${oldname.split(".").pop()}`;

    // 要转换倍速的文件
    let filepath = path.resolve(findPath, oldname);

    if (!fs.existsSync(filepath)) {
        return res.send({ code: 400, msg: `路径 ${filepath} 不存在！`, result: '', ...req.body });
    }

    if (!fs.existsSync(outputPath)) {
        try {
            fs.mkdirSync(outputPath, { recursive: true });
        } catch (error) {
            return res.send({ code: 400, msg: "输出路径错误！", result: '', ...req.body });
        }
    }

    new Promise((resolve, reject) => {

        let savePath = path.resolve(outputPath, newname);

        if (fs.existsSync(savePath)) {
            return reject("目标目录下存在同名文件！！！")
        };

        let cmd = `"${ffmpegPath}" -i "${filepath}" -filter_complex "[0:v]setpts=${speedMap.get(speed)}*PTS[v];[0:a]atempo=${speed}[a]" -map "[v]" -map "[a]" "${savePath}"`;

        exec(cmd, (err, stdout, stderr) => {
            if (err) return reject(err);
            if (/^true$/i.test(delSource)) fs.unlinkSync(filepath);
            resolve({ savePath, newname });
        })

    }).then(({ savePath, newname }) => {
        exec(`explorer "${outputPath}"`, (err, stdout, stderr) => {
            if (err) console.log(err);
        })
        res.send({
            code: 200,
            state: true,
            currentIndex,
            filename: newname,
            result: savePath,
            msg: `${newname} 变速成功！`
        })
    }).catch(err => {
        console.log(err);
        res.send({
            code: 500,
            state: false,
            currentIndex,
            filename: newname,
            result: err,
            msg: `${newname} 变速失败！`
        })
    })

}